﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Net.Http;
using OurDailyBread.Helpers;
using Windows.Data.Json;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.Net.Http.Headers;
using Newtonsoft.Json.Converters;

namespace OurDailyBread.Model
{
    public class CommentDataService : ICommentDataService
    {
        //string breadWebAPIUri = "http://localhost:50243/api/comments";
        string breadWebAPIUri = "http://breadwebapi.azurewebsites.net/api/comments";

        public async void GetData(DateTime commentTime, Action<Object, Exception> callback)
        {
            // Use this to connect to the actual data service
            try
            {
                string BreadDate = Util.GetShortNavUrl(commentTime);
                string url = breadWebAPIUri + "?BreadDate=" + BreadDate;
                string getResults = await HttpService.Get(new Uri(url));

                //IEnumerable<CommentData> results = JsonConvert.DeserializeObject<IEnumerable<CommentData>>(getResults);

                callback(getResults, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }

        }

        public async void PutData(DateTime commentTime, string commentText, Action<Object, Exception> callback)
        {
            // Use this to connect to the actual data service
            try
            {
                HttpResponseMessage msg;

                CommentData comment = new CommentData();
                comment.PartitionKey = commentTime.ToString("yyyyMMdd");
                comment.RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks, Guid.NewGuid());
                comment.BreadUrl = Util.GetShortNavUrl(commentTime);
                comment.Comment = commentText;

                string jsonComment = JsonConvert.SerializeObject(comment);
                StringContent content = new StringContent(jsonComment,Encoding.UTF8,"application/json");

                using (var client = new HttpClient())
                { 
                    msg = await client.PostAsync(new Uri(breadWebAPIUri), content);
                }

                callback(msg, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }

        }
    }
}